from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
                               QPushButton, QFrame, QTextEdit, QMessageBox)
from PySide6.QtGui import QFont, QPalette, QColor
from PySide6.QtCore import Qt
import os
from database.db_manager import DBManager



import pygame
import pyaudio

import requests
def play_audio(url):
    """播放音频"""

    p = pyaudio.PyAudio()
# 创建音频流
    response = requests.get('http://www.example.com/music.mp3')

# 打开音频输出
    stream = p.open(format=p.get_format_from_width(2),
                    channels=2,
                    rate=44100,
                    output=True)

# 播放音频
    stream.write(response.content)

# 停止数据流
    stream.stop_stream()
    stream.close()

# 关闭PyAudio
    p.terminate()


    pygame.time.Clock().tick(10)
def download_file(url, save_path):
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            with open(save_path, 'wb') as f:
                f.write(response.content)
            return True
        return False
class WordCardWidget(QWidget):
    """单词卡片组件，支持翻转效果"""
    
    def __init__(self, db_manager: DBManager, parent=None):
        super().__init__(parent)
        self.db_manager = db_manager
        self.current_word = None
        self.is_flipped = False
        self.init_ui()
        
    def init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setAlignment(Qt.AlignCenter)
        
        # 创建卡片容器
        self.card_container = QWidget()
        self.card_container.setMinimumSize(600, 400)
        self.card_container.setMaximumSize(800, 500)
        self.card_layout = QVBoxLayout(self.card_container)
        
        # 创建卡片两面
        self.front_card = self.create_card_side("front")
        self.back_card = self.create_card_side("back")
        
        # 默认显示正面
        self.card_layout.addWidget(self.front_card)
        self.back_card.hide()
        
        layout.addWidget(self.card_container)
        
        # 创建按钮布局
        btn_layout = QHBoxLayout()
        
        self.btn_prev = QPushButton("上一个")
        self.btn_prev.clicked.connect(self.prev_word)
        
        self.btn_flip = QPushButton("查看释义")
        self.btn_flip.clicked.connect(self.flip_card)
        
        self.btn_know = QPushButton("认识")
        self.btn_know.setStyleSheet("background-color: #34c759;")
        self.btn_know.clicked.connect(lambda: self.mark_mastery(2))
        
        self.btn_half = QPushButton("模糊")
        self.btn_half.setStyleSheet("background-color: #ffcc00; color: black;")
        self.btn_half.clicked.connect(lambda: self.mark_mastery(1))
        
        self.btn_not_know = QPushButton("不认识")
        self.btn_not_know.setStyleSheet("background-color: #ff3b30;")
        self.btn_not_know.clicked.connect(lambda: self.mark_mastery(0))
        
        # 设置按钮最小高度
        for btn in [self.btn_prev, self.btn_flip, self.btn_not_know, self.btn_half, self.btn_know]:
            btn.setMinimumHeight(40)
            btn_layout.addWidget(btn)
            
        layout.addLayout(btn_layout)
        
        # 获取第一个单词
        self.refresh_data()
        
    def create_card_side(self, side: str) -> QWidget:
        """创建卡片的一面"""
        card = QFrame()
        card.setObjectName(f"card_{side}")
        card.setStyleSheet('''
            QFrame {
                background-color: white;
                border-radius: 16px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1)
            }
        ''')
        
        layout = QVBoxLayout(card)
        layout.setContentsMargins(30, 30, 30, 30)
        
        if side == "front":
            # 正面内容：单词和音标
            self.lbl_word = QLabel()
            self.lbl_word.setObjectName("word_label")
            self.lbl_word.setStyleSheet("font-size: 36px; font-weight: bold; color: #1c1c1e;")
            self.lbl_word.setAlignment(Qt.AlignCenter)
            
            self.lbl_phonetic = QLabel()
            self.lbl_phonetic.setObjectName("phonetic_label")
            self.lbl_phonetic.setStyleSheet("font-size: 18px; color: #6e6e73; margin: 10px 0;")
            self.lbl_phonetic.setAlignment(Qt.AlignCenter)
            
            layout.addStretch()
            layout.addWidget(self.lbl_word)
            layout.addWidget(self.lbl_phonetic)
            layout.addStretch()
            
        else:
            # 背面内容：释义和例句
            self.lbl_meaning = QTextEdit()
            self.lbl_meaning.setObjectName("meaning_label")
            self.lbl_meaning.setStyleSheet("font-size: 18px; color: #1c1c1e;")
            self.lbl_meaning.setReadOnly(True)
            self.lbl_meaning.setFrameShape(QFrame.NoFrame)
            
            self.lbl_example = QTextEdit()
            self.lbl_example.setObjectName("example_label")
            self.lbl_example.setStyleSheet("font-size: italic; color: #6e6e73; margin-top: 20px;")
            self.lbl_example.setReadOnly(True)
            self.lbl_example.setFrameShape(QFrame.NoFrame)
            
            layout.addWidget(self.lbl_meaning)
            layout.addWidget(self.lbl_example)
            
        return card
    
    def refresh_data(self):
        """刷新卡片数据，获取下一个待复习单词"""
        # 确保按钮初始状态为启用
        self.enable_buttons(True)
        
        words = self.db_manager.get_words_to_review(1)
        
        if words:
            self.current_word = words[0]
            self.update_card_content()
            self.is_flipped = False
            self.back_card.hide()
            self.front_card.show()
            self.btn_flip.setText("查看释义")
            word = self.current_word["word"]
            os.makedirs("mp3temp", exist_ok=True)
            
            play_audio(f"http://dict.youdao.com/dictvoice?type=1&audio={word}")
        else:
            self.show_empty_state()
            
    def update_card_content(self):
        """更新卡片内容"""
        if not self.current_word:
            return
            
        # 更新正面内容
        self.lbl_word.setText(self.current_word['word'])
        self.lbl_phonetic.setText(self.current_word['phonetic'] or "无音标")
        
        # 更新背面内容
        meaning_text = f"<b>释义：</b>{self.current_word['meaning']}"
        self.lbl_meaning.setHtml(meaning_text)
        
        example_text = f"<b>例句：</b>{self.current_word['example'] or '无例句'}"
        self.lbl_example.setHtml(example_text)
        
    def show_empty_state(self):
        """显示空状态（没有待复习单词）"""
        self.current_word = None
        self.lbl_word.setText("📚 准备学习")
        self.lbl_phonetic.setText("暂无待复习单词")
        self.lbl_meaning.setHtml("<b>请先导入单词库或添加单词</b><br><br>1. 点击顶部的\"导入词库\"按钮<br>2. 选择JSON格式的单词文件")
        self.lbl_example.setHtml("")
        
        # 仅禁用评分按钮，保留翻页和查看按钮可用
        self.btn_not_know.setEnabled(False)
        self.btn_half.setEnabled(False)
        self.btn_know.setEnabled(False)
        
        # 显示提示信息
        QMessageBox.information(self, "提示", "当前没有待复习的单词，请先导入单词库。")
        
    def enable_buttons(self, enable: bool):
        """启用或禁用所有按钮"""
        self.btn_prev.setEnabled(enable)
        self.btn_flip.setEnabled(enable)
        self.btn_not_know.setEnabled(enable)
        self.btn_half.setEnabled(enable)
        self.btn_know.setEnabled(enable)
            
    def flip_card(self):
        """翻转卡片"""
        if not self.current_word:
            # 即使没有单词也允许翻转查看说明
            self.is_flipped = not self.is_flipped
            
            if self.is_flipped:
                self.front_card.hide()
                self.back_card.show()
                self.btn_flip.setText("查看单词")
            else:
                self.back_card.hide()
                self.front_card.show()
                self.btn_flip.setText("查看释义")
            return
            
        self.is_flipped = not self.is_flipped
        
        if self.is_flipped:
            self.front_card.hide()
            self.back_card.show()
            self.btn_flip.setText("查看单词")
        else:
            self.back_card.hide()
            self.front_card.show()
            self.btn_flip.setText("查看释义")
            
    def mark_mastery(self, level: int):
        """标记单词掌握程度"""
        if not self.current_word:
            QMessageBox.warning(self, "无法操作", "没有可评分的单词，请先导入单词库。")
            return
            
        # 更新单词掌握程度
        success, message = self.db_manager.update_word_mastery(self.current_word['id'], level)
        if success:
            # 获取下一个单词
            self.refresh_data()
        else:
            QMessageBox.error(self, "操作失败", message)
        
    def prev_word(self):
        """上一个单词（预留功能）"""
        QMessageBox.information(self, "提示", "此功能将在后续版本中添加，敬请期待！")